using SmartCommunity.Models;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace SmartCommunity.Services.Community
{
    /// <summary>
    /// 服务类：小区
    /// </summary>
    public class AreaService : BaseService<AreaEntity>
    {
        #region 构造函数
        protected readonly SCDBContext ctx;
        public AreaService(SCDBContext ctx)
        {
            this.ctx = ctx;
        }
        #endregion

        #region 数据查询 
        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<PageResult<AreaDto>> FindPagedList(AreaQuery areaQuery, Pager pager, LoginUser user)
        {
            //TODO 小区权限
            var query = ctx.Areas.AsNoTracking().Where(areaQuery.GetQueryExpression());
            var data = await FindPagedList(query, pager, o => o.OrderByDescending(t => t.CreatedTime));
            return data.Map(o => o.Adapt<AreaDto>());
        }

        /// <summary>
        /// 根据小区ID查询
        /// </summary>
        public async Task<AreaDto> FindAreaById(Guid areaId)
        {
            var entity = await FindById(areaId);
            return entity.Adapt<AreaDto>();
        }

        /// <summary>
        /// 根据ID查询实体类
        /// </summary>
        private async Task<AreaEntity> FindById(Guid id)
        {
            return await ctx.Areas.SingleOrDefaultAsync(a => a.AreaId == id)
                ?? throw new NotFoundException($"找不到指定的小区,Id:{id}");
        }
        #endregion

        #region 增 删 改
        /// <summary>
        /// 新增小区
        /// </summary>
        public async Task<AreaDto> CreateArea(AreaDto dto, LoginUser user)
        {
            // 新建对象
            var entity = new AreaEntity();
            // 复制属性
            await CopyDtoToEntity(dto, entity, user, true);
            // 执行保存
            ctx.Areas.Add(entity);
            await ctx.SaveChangesAsync();
            // 返回Dto
            return entity.Adapt<AreaDto>();
        }

        /// <summary>
        /// 更新小区
        /// </summary>
        public async Task UpdateArea(AreaDto dto, LoginUser user)
        {
            // 原始数据
            var entity = await FindById(dto.AreaId);
            // 更新字段
            await CopyDtoToEntity(dto, entity, user, false);
            // 执行更新
            await ctx.SaveChangesAsync();
        }

        /// <summary>
        /// 复制dto属性到实体字段
        /// </summary>
        private async Task CopyDtoToEntity(AreaDto dto, AreaEntity entity, LoginUser user, bool isNew)
        {
            //TODO 检查数据重复
            if (await ctx.Areas.AnyAsync(a => a.AreaId != dto.AreaId && (a.CommunityId == dto.CommunityId && a.AreaName == dto.AreaName.Trim())))
            {
                throw new MessageException("当前社区已存在相同名称的小区");
            }
            entity.AreaName = dto.AreaName.Trim();
            entity.CommunityId = dto.CommunityId;
            var community = await ctx.Communities.FindAsync(dto.CommunityId);
            entity.CommunityName = community!.CommunityName;
            entity.AreaAddr = dto.AreaAddr;
            entity.BuildArea = dto.BuildArea;
            entity.PlantArea = dto.PlantArea;
            entity.TotalArea = dto.TotalArea;
            entity.SortNo = dto.SortNo;
            entity.Remark = dto.Remark;
            entity.Disabled = dto.Disabled;

            // 记录操作人
            if (isNew)
            {
                entity.CreatedBy = user.Username;
                entity.CreatedTime = DateTime.Now;
            }
            entity.UpdatedBy = user.Username;
            entity.UpdatedTime = DateTime.Now;
        }

        /// <summary>
        /// 根据ID删除小区
        /// </summary>
        public async Task DeleteByIds(IEnumerable<Guid> ids, LoginUser user)
        {
            var areas = await ctx.Areas.Where(a => ids.Contains(a.AreaId)).ToListAsync();
            if (areas.Count != ids.Count())
            {
                throw new MessageException("查询出的数据和传入的ID不匹配，请刷新后再试。");
            }
            //TODO 判断是否能删除
            foreach (var entity in areas)
            {
                ctx.Areas.Remove(entity);
            }
            // 提交事务
            await ctx.SaveChangesAsync();
        }
        #endregion
    }
}
